package zhr.chapter13.zuoye;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class server {
    public static void main(String[] args) throws Exception {
        new server.TCPserver().listen();
    }

    static class TCPserver {
        private static final int PORT = 7788;

        public void listen() throws Exception {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("服务器启动，等待客户端连接...");

            while (true) { // 保持监听状态
                Socket client = serverSocket.accept();
                System.out.println("客户端连接成功");

                // 发
                OutputStream os = client.getOutputStream();
                // 收
                InputStream osin = client.getInputStream();
                System.out.println("开始与客户端交互数据");

                os.write(("服务器欢迎您!").getBytes());

                byte[] buf = new byte[1024];
                int len = osin.read(buf);
                String receivedData = new String(buf, 0, len).trim();

                String[] parts = receivedData.split(",");
                if (parts.length != 3) {
                    os.write(("错误：数据格式不正确").getBytes());
                    return;
                }

                try {
                    double a = Double.parseDouble(parts[0].trim());
                    double b = Double.parseDouble(parts[1].trim());
                    double c = Double.parseDouble(parts[2].trim());

                    String result = calculateTriangle(a, b, c);
                    os.write(("计算结果: " + result).getBytes());
                } catch (NumberFormatException e) {
                    os.write(("错误：输入的边长格式不正确").getBytes());
                }

                System.out.println("结束与客户端的数据交互");
                os.close();
                client.close();
            }
        }

        public static String calculateTriangle(double a, double b, double c) {
            if (!isValidTriangle(a, b, c)) {
                return "不能构成三角形";
            }

            double perimeter = a + b + c;
            double area = calculateArea(a, b, c);
            return "周长: " + perimeter + ", 面积: " + area;
        }

        private static boolean isValidTriangle(double a, double b, double c) {
            return a + b > c && a + c > b && b + c > a;
        }

        private static double calculateArea(double a, double b, double c) {
            double s = (a + b + c) / 2;
            return Math.sqrt(s * (s - a) * (s - b) * (s - c));
        }
    }
}